<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :options="editorOption"
       :mode="mode"
    />
    <Editor
      style="height: 130px; overflow-y: hidden"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
       :mode="mode"
      @onCreated="handleCreated"
    />
  </div>
</template>
<script setup>
import "@wangeditor/editor/dist/css/style.css"; // 引入 css

import {
  onBeforeUnmount,
  ref,
  shallowRef,
  onMounted,
  defineEmits,
  inject,
  watchEffect,
  watch,
} from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";

import { DomEditor } from "@wangeditor/editor";
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
// 子给父传值
const emit = defineEmits(["edi"]);
// 内容 HTML
const valueHtml = ref("<p></p>");
// 父页面数据
const dataDrawer = inject("dataDrawer");
const props = defineProps({
  title:{
    type:String
  }
}) 
let arr = [];
watchEffect(() => {
  // console.log(124,dataDrawer.params.title)
  dataDrawer.params.title = valueHtml.value;
  if (valueHtml.value.match(/\[\]/g) !== null) {
    arr = valueHtml.value.match(/\[\]/g);
    emit("is", arr);
  } else {
    arr = [];
  }
});

const toolbarConfig = {
  toolbarKeys: [
    // 菜单 key
    "bold",
    "italic",
    "underline",
    "through",
    "color",
    "bgColor",
    "bulletedList",
    "numberedList",
    "justifyLeft",
    "justifyCenter",
    "justifyRight",
    "insertTable",
    // 继续配置其他菜单...
    {
      key: "group-image", // 必填，要以 group 开头
      title: "图片", // 必填
      menuKeys: ["uploadImage", "insertImage"],
    },
  ],
};
const editorConfig = {  MENU_CONF: {}};

editorConfig.MENU_CONF['uploadImage'] = {
  server: import.meta.env.VITE_BASE_URL+'upload/editeradd', // 上传图片地址
  timeout: 5 * 1000, // 5s
  fieldName: 'file',
  meta: { baseUrl: '' },
  metaWithUrl: true, // 参数拼接到 url 上
  headers: { Authorization:sessionStorage.getItem('token') },

  maxFileSize: 10 * 1024 * 1024, // 10M

  base64LimitSize: 5 * 1024, // 5kb 以下插入 base64

  onBeforeUpload(files) {
    console.log('onBeforeUpload', files)
    return files // 返回哪些文件可以上传
  },
  onProgress(progress) {
    console.log('onProgress', progress)
  },
  onSuccess(file, res) {
    console.log('onSuccess', file, res)
  },
  onFailed(file, res) {
    alert(res.message)
    console.log('onFailed', file, res)
  },
  onError(file, err, res) {
    alert(err.message)
    console.error('onError', file, err, res)
  },
  // // 用户自定义插入图片
  customInsert(res,insertFn) {
    var Img = res.data[0].url.slice(1)
    // 自己插入图片
    // console.log('自己插入图片', url)
    // insertFn(url, alt, href)
    insertFn("http://www.eshareedu.cn/exam/upload/" + Img)
  },
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};

</script>